import argparse
import os
import logging

from scapy.all import get_if_list

from .recorder import FlowRecorder
from .config import config

LOGGER = logging.getLogger(__name__)


def run():
    flow_recorder = FlowRecorder()
    if config.capture:
        if not config.interface:
            config.interface = choose_interface()
        flow_recorder.run_live()
        LOGGER.info("Capture done, %d http/tls packets in total", flow_recorder.packets_processed)

    if config.analyze:
        if not config.capture:
            flow_recorder.load(config.pcapng_analyze_catalog)
        flow_recorder.analyze()


def choose_interface():
    interfaces = get_if_list()

    print("Avalible Interface:")
    for index, iface in enumerate(interfaces):
        print(f"{index}: {iface}")

    while True:
        choice = input("请选择一个接口（输入编号）: ")
        try:
            selected_iface = interfaces[int(choice)]
            break
        except (ValueError, IndexError):
            print("无效的选择。")

    return selected_iface

###################
# Argument parser #
###################


parser = argparse.ArgumentParser(
    description="Packet capturer and analyzer")
parser.add_argument('-c', '--capture',
                    action='store_true', help="启动抓包")
parser.add_argument('-a', '--analyze',
                    action='store_true', help="启动抓包后的分析")
parser.add_argument('-i', '--interface', type=str, help="指定抓包的接口")

default_config_path = os.path.join(os.getcwd(), 'config', 'config.yaml')
parser.add_argument('-y', '--yaml', type=str, default=default_config_path,
                    help="指定配置文件路径，默认为 ./config/config.yaml")

parser.add_argument('-n', '--numbers', type=int,
                    default=0, help="抓包上限，不指定默认为0即无上限")

args = parser.parse_args()
config.init(args)
